from meiduo_mall.utils import meiduo_json
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response):
    cart = request.COOKIES.get('cart')
    if not cart:
        return
    cart = meiduo_json.loads(cart)

    # 保存数据到redis中
    redis = get_redis_connection('carts')

    for sku_id, info in cart.items():
        count = info['count']
        selected = info['selected']

        # 如果商品在redis中已经存在，则覆盖redis中的购物车数据
        redis.hset('carts:%d' % request.user.id, sku_id, count)

        # 更新商品选中状态
        if selected:
            redis.sadd('selected:%d' % request.user.id, sku_id)
        else:
            redis.srem('selected:%d' % request.user.id, sku_id)

    response.delete_cookie('cart')


